package servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.BookDao;
import dao.impl.BookDaoImpl;
import model.Book;
import util.DateConvert;

/**
 * Servlet implementation class BookServlet
 */
@WebServlet("/BookServlet")
public class BookServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private BookDao bd;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public BookServlet() {
		super();
		bd = new BookDaoImpl();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String action = (String) request.getParameter("action");
		try {
			if (action.equals("addbook")) {
				addbook(request, response);
			}else if(action.equals("deletebook")){
				deletebook(request, response);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

	protected void addbook(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, SQLException {
		String BookName = request.getParameter("BookName");
		String BookIsbn = request.getParameter("BookIsbn");
		String BookAuthor = request.getParameter("BookAuthor");
		String BookPurchase = request.getParameter("BookPurchase");
		String BookPrice = request.getParameter("BookPrice");
		String bookPublishingTime = request.getParameter("bookPublishingTime");
		String BookNum = request.getParameter("BookNum");
		Book book = new model.Book();
		book.setBookName(BookName);
		book.setBookIsbn(BookIsbn);
		book.setBookAuthor(BookAuthor);
		book.setBookPurchase(Float.parseFloat(BookPurchase));
		book.setBookPrice(Float.parseFloat(BookPrice));
		book.setBookPublishingTime(DateConvert.stringToDate(bookPublishingTime));
		book.setBookNum(Integer.parseInt(BookNum));
		if (bd.addBook(book)) {
			response.sendRedirect("index.jsp");
		}else {
			response.sendRedirect("pages/addbook.jsp");
		}
	}
	
	protected void deletebook(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, SQLException {
		String BookIsbn = request.getParameter("BookIsbn");
		Book book = new model.Book();
		book.setBookIsbn(BookIsbn);
		bd.deletebook(book);
		response.sendRedirect("index.jsp");
	}

}
